import hashlib

from flask import request, jsonify, Blueprint, url_for, redirect
from flask_jwt_extended import (
    create_access_token,
    create_refresh_token, jwt_required, get_jwt_identity,
)

from database import db
from modal import User
from utils import fail_api, auto_model_jsonify

bp = Blueprint('user', __name__, url_prefix='/user')


@bp.post('/login')
def login():
    data = request.get_json()
    email = data.get('email')
    password = data.get('password')

    # 检查用户是否存在
    user = User.query.filter_by(email=email).first()

    if not user or user.password.upper() != password.upper():
        return fail_api("用户不存在或密码错误")

    access_token = create_access_token(identity=user.email)
    refresh_token = create_refresh_token(identity=user.email)
    return jsonify({"access_token": access_token, "refresh_token": refresh_token})


@bp.get('/refresh')
@jwt_required(refresh=True)
def refresh():
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    return jsonify({"access_token": access_token})


@bp.get('/info')
@jwt_required()
def info():
    current_user = get_jwt_identity()
    user = User.query.filter_by(email=current_user).first()

    user_info = auto_model_jsonify(model=User, data=user)
    user_info.pop('password')

    return user_info


# https://densimetric-hunter-combustive.ngrok-free.app/user/auth2/login
@bp.get('/auth2/login')
def login_google():
    from app import oauth
    google = oauth.create_client('google')

    if google:
        redirect_uri = url_for('user.authorize_google', _external=True)
        return google.authorize_redirect(redirect_uri)
    return fail_api("登录失败")


@bp.get('/auth2/info')
def authorize_google():
    from app import oauth
    google = oauth.create_client('google')

    token = google.authorize_access_token()
    resp = google.get('userinfo')
    user_info = resp.json()

    user = User.query.filter_by(email=user_info['email']).first()
    if user is None:
        md5_password = hashlib.md5('123456'.encode()).hexdigest().upper()
        user = User(email=user_info['email'], password=md5_password, name=user_info['name'],
                    avatar=user_info['picture'])
        db.session.add(user)
        db.session.commit()

    access_token = create_access_token(identity=user.email)
    refresh_token = create_refresh_token(identity=user.email)
    frontend_url = "http://localhost:5173"  # 前端地址
    redirect_url = f"{frontend_url}?access_token={access_token}&refresh_token={refresh_token}"
    return redirect(redirect_url)
